package com.admin.infrastructure.persistence.jdbc;

import com.admin.domain.modle.Order;
import com.admin.domain.modle.OrderSeat;
import com.admin.domain.repository.OrderRepository;
import com.admin.infrastructure.DateUtils;
import com.admin.interfaces.facade.dto.OrderQueryDTO;
import com.admin.utils.OrderStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * description User: WeiDa Date: 2017-4-13 Time: 20:38
 */
@Repository
public class OrderRepositoryJdbc implements OrderRepository {

	@Autowired
	protected JdbcTemplate jdbcTemplate;

	@Override
	public void add(Order order) {
		jdbcTemplate.update("INSERT INTO t_order (id) VALUES (?,?,?,?)",
				order.getId());
	}

	@Override
	public void update(Order order) {
		jdbcTemplate.update(
				"UPDATE t_order SET title=?,url=?,img_url=? WHERE `id`=?",
				order.getPlayId(), order.getPlayDate(), order.getId());
	}

	@Override
	public Order get(String id) {
		return jdbcTemplate.queryForObject(
				"select * from `t_order` where `id`=?",
				BeanPropertyRowMapper.newInstance(Order.class), id);
	}

	@Override
	public Order getOrder(int orderId) {
		return jdbcTemplate.queryForObject(
				"select * from `t_order` where `order_id`=?",
				BeanPropertyRowMapper.newInstance(Order.class), orderId);
	}

	@Override
	public List<OrderSeat> getOrderSeats(int orderId) {
		return jdbcTemplate.query(
				"select * from `order_seat` where `order_id`=?",
				BeanPropertyRowMapper.newInstance(OrderSeat.class), orderId);
	}

	@Override
	public List<Order> list(OrderQueryDTO queryDTO) {
		StringBuilder sql = new StringBuilder(
				"select * from `t_order` where 1=1");
		if (!StringUtils.isEmpty(queryDTO.getOrderId())) {
			sql.append(" and order_id=").append("'")
					.append(queryDTO.getOrderId()).append("'");
		}
		if (!StringUtils.isEmpty(queryDTO.getPlayName())) {
			sql.append(" and play_name like ").append("'%")
					.append(queryDTO.getPlayName()).append("%'");
		}
		if (!StringUtils.isEmpty(queryDTO.getNickName())) {
			sql.append(" and nick_name like ").append("'%")
					.append(queryDTO.getNickName()).append("%'");
		}
		if (!StringUtils.isEmpty(queryDTO.getStatus())) {
			sql.append(" and status=").append("'").append(queryDTO.getStatus())
					.append("'");
		}
		if (!StringUtils.isEmpty(queryDTO.getOpenId())) {
			sql.append(" and open_id=").append("'")
					.append(queryDTO.getOpenId()).append("'");
		}
		if (queryDTO.getStartTime() != null) {
			sql.append(" and create_time >=").append("'")
					.append(DateUtils.formaterDate(queryDTO.getStartTime()))
					.append("'");
		}
		if (queryDTO.getEndTime() != null) {
			sql.append(" and create_time <=").append("'")
					.append(DateUtils.formaterDate(queryDTO.getEndTime()))
					.append("'");
		}
		return jdbcTemplate.query(sql.toString(),
				BeanPropertyRowMapper.newInstance(Order.class));
	}

	@Override
	public void remove(String id) {
		jdbcTemplate.update("DELETE FROM t_order WHERE id=?", id);
	}

	@Override
	public void delete(int orderId) {
		jdbcTemplate.update("DELETE FROM t_order WHERE order_id=?", orderId);
	}

	@Override
	public int upsert(Order order) {
		StringBuilder sql = new StringBuilder();
		sql.append("INSERT INTO `t_order` (`id`, `order_id`, `play_id`, `play_name`, `play_date`, `play_code`, `play_image`, `open_id`, `nick_name`, `quantity`, `status`, `pay_amount`, `pay_time`, `remark`, `name`, `phone`, `trade_no`, `user_id`) ");
		sql.append("VALUES (?, ?, ?, ?,?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?, ?, ? ,?)");
		sql.append(" ON DUPLICATE KEY UPDATE ");
		sql.append("play_id=ifnull(values(play_id),play_id),");
		sql.append("play_name=ifnull(values(play_name),play_name),");
		sql.append("play_date=ifnull(values(play_date),play_date),");
		sql.append("play_code=ifnull(values(play_code),play_code),");
		sql.append("play_image=ifnull(values(play_image),play_image),");
		sql.append("open_id=ifnull(values(open_id),open_id),");
		sql.append("nick_name=ifnull(values(nick_name),nick_name),");
		sql.append("quantity=ifnull(values(quantity),quantity),");
		sql.append("status=ifnull(values(status),status),");
		sql.append("pay_amount=ifnull(values(pay_amount),pay_amount),");
		sql.append("pay_time=ifnull(values(pay_time),pay_time),");
		sql.append("remark=ifnull(values(remark),remark),");
		sql.append("name=ifnull(values(name),name),");
		sql.append("phone=ifnull(values(phone),phone),");
		sql.append("trade_no=ifnull(values(trade_no),trade_no),");
		sql.append("user_id=ifnull(values(user_id),user_id)");
		return jdbcTemplate.update(sql.toString(), order.getId(),
				order.getOrderId(), order.getPlayId(), order.getPlayName(),
				order.getPlayDate(), order.getPlayCode(), order.getPlayImage(),
				order.getOpenId(), order.getNickName(), order.getQuantity(),
				order.getStatus(), order.getPayAmount(), order.getPayTime(),
				order.getRemark(), order.getName(), order.getPhone(),
				order.getTradeNo(),order.getUserId());
	}

	@Override
	public int deleteSeat(int orderId) {
		return jdbcTemplate.update("DELETE FROM order_seat WHERE order_id=?",
				orderId);
	}

	@Override
	public int saveSeats(List<OrderSeat> seats) {
		StringBuilder sql = new StringBuilder();
		sql.append("INSERT INTO `order_seat` (`id`, `order_id`, `price`, `name`, `seat_id`, `floor`)");
		sql.append("VALUES (?, ?, ?, ?, ?, ?)");
		OrderSeat seat = seats.get(0);
		Object[] params = new Object[6 * seats.size()];
		params[0] = seat.getId();
		params[1] = seat.getOrderId();
		params[2] = seat.getPrice();
		params[3] = seat.getName();
		params[4] = seat.getSeatId();
		params[5] = seat.getFloor();
		for (int i = 1; i < seats.size(); i++) {
			seat = seats.get(i);
			sql.append(",(?,?,?,?,?,?)");
			System.arraycopy(
					new Object[] { seat.getId(), seat.getOrderId(),
							seat.getPrice(), seat.getName(), seat.getSeatId(),
							seat.getFloor() }, 0, params, i * 6, 6);
		}
		return jdbcTemplate.update(sql.toString(), params);
	}

	@Override
	public int updateWhenPaying(int orderId, String tradeNo, String uname,
			String phone) {
		return jdbcTemplate
				.update("update `t_order` set status = ?,name = ?,phone = ?,trade_no = ? where order_id = ?",
						OrderStatus.INIT.name(), uname, phone, tradeNo, orderId);
	}

	@Override
	public int updateWhenPaid(String tradeNo, Date payTime) {
		return jdbcTemplate
				.update("update `t_order` set status = ?,pay_time = ? where trade_no = ?",
						OrderStatus.PAID.name(), payTime, tradeNo);
	}

	@Override
	public int cancelOrder(int orderId) {
		return jdbcTemplate.update(
				"update `t_order` set status = ? where order_id = ?",
				OrderStatus.CANCEL.name(), orderId);
	}

	@Override
	public int updateRemark(String id, String remark) {
		return jdbcTemplate.update(
				"update `t_order` set remark = ? where id = ?", remark, id);
	}

	@Override
	public List<Order> listByStatus(String status) {
		return jdbcTemplate.query(
				"select * from `t_order` where `status` = ?",
				BeanPropertyRowMapper.newInstance(Order.class), status);
	}

	@Override
	public List<Order> listByStatusAndUserId(String status,String userId) {
		return jdbcTemplate.query(
				"select * from `t_order` where `status` = ? and `user_id` = ?" ,
				BeanPropertyRowMapper.newInstance(Order.class), status,userId);
	}

	@Override
	public int verifyOrder(Integer orderId) {
		return jdbcTemplate.update(
				"update `t_order` set status = ? where order_id = ?",
				OrderStatus.VERIFIED.name(), orderId);
	}
}
